import React, { useState, useEffect } from 'react'
import { 
  Layout, 
  Table, 
  Card, 
  Button, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Select, 
  message,
  Popconfirm,
  Tooltip
} from 'antd'
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined,
  UserOutlined,
  MailOutlined,
  LockOutlined
} from '@ant-design/icons'
import { userAPI } from '../services/api'

const { Content } = Layout
const { Option } = Select

const UserManagement = () => {
  const [users, setUsers] = useState([])
  const [loading, setLoading] = useState(false)
  const [modalVisible, setModalVisible] = useState(false)
  const [editingUser, setEditingUser] = useState(null)
  const [form] = Form.useForm()

  useEffect(() => {
    fetchUsers()
  }, [])

  const fetchUsers = async () => {
    setLoading(true)
    try {
      const response = await userAPI.getUsers({ page_size: 100 })
      if (response.code === 200) {
        setUsers(response.data?.users || [])
      } else {
        message.error('获取用户列表失败')
      }
    } catch (error) {
      message.error('获取用户列表失败')
    } finally {
      setLoading(false)
    }
  }

  const handleCreate = () => {
    setEditingUser(null)
    form.resetFields()
    setModalVisible(true)
  }

  const handleEdit = (user) => {
    setEditingUser(user)
    form.setFieldsValue({
      username: user.username,
      email: user.email,
      role: user.role
    })
    setModalVisible(true)
  }

  const handleDelete = async (userId) => {
    try {
      const response = await userAPI.deleteUser(userId)
      if (response.code === 200) {
        message.success('用户删除成功')
        fetchUsers()
      } else {
        message.error(response.message || '用户删除失败')
      }
    } catch (error) {
      message.error('用户删除失败')
    }
  }

  const handleResetPassword = async (userId) => {
    try {
      const response = await userAPI.resetUserPassword(userId)
      if (response.code === 200) {
        message.success('密码重置成功')
      } else {
        message.error(response.message || '密码重置失败')
      }
    } catch (error) {
      message.error('密码重置失败')
    }
  }

  const handleSubmit = async (values) => {
    try {
      let response
      if (editingUser) {
        response = await userAPI.updateUser(editingUser.id, values)
      } else {
        response = await userAPI.createUser(values)
      }

      if (response.code === 200 || response.code === 201) {
        message.success(editingUser ? '用户更新成功' : '用户创建成功')
        setModalVisible(false)
        fetchUsers()
      } else {
        message.error(response.message || '操作失败')
      }
    } catch (error) {
      message.error('操作失败')
    }
  }

  const getRoleTag = (role) => {
    const roleConfig = {
      super_admin: { color: 'red', text: '超级管理员' },
      user: { color: 'blue', text: '普通用户' }
    }
    
    const config = roleConfig[role] || { color: 'default', text: role }
    return <Tag color={config.color}>{config.text}</Tag>
  }

  const columns = [
    {
      title: '用户ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role) => getRoleTag(role)
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (time) => new Date(time).toLocaleString()
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="编辑">
            <Button 
              type="link" 
              icon={<EditOutlined />} 
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title="重置密码">
            <Popconfirm
              title="确定要重置这个用户的密码吗？"
              onConfirm={() => handleResetPassword(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button 
                type="link" 
                icon={<LockOutlined />}
              />
            </Popconfirm>
          </Tooltip>
          {record.role !== 'super_admin' && (
            <Tooltip title="删除">
              <Popconfirm
                title="确定要删除这个用户吗？"
                description="删除用户将同时删除该用户的所有设备"
                onConfirm={() => handleDelete(record.id)}
                okText="确定"
                cancelText="取消"
              >
                <Button 
                  type="link" 
                  danger 
                  icon={<DeleteOutlined />} 
                />
              </Popconfirm>
            </Tooltip>
          )}
        </Space>
      ),
    },
  ]

  return (
    <Layout>
      <Content style={{ padding: '24px' }}>
        <Card
          extra={
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={handleCreate}
            >
              创建用户
            </Button>
          }
        >
          <Table
            columns={columns}
            dataSource={users}
            rowKey="id"
            loading={loading}
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`,
            }}
          />
        </Card>

        {/* 创建用户/编辑用户模态框 */}
        <Modal
          title={editingUser ? '编辑用户' : '创建用户'}
          open={modalVisible}
          onCancel={() => setModalVisible(false)}
          footer={null}
          width={600}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
          >
            <Form.Item
              name="username"
              label="用户名"
              rules={[
                { required: true, message: '请输入用户名' },
                { min: 3, message: '用户名至少3个字符' }
              ]}
            >
              <Input 
                prefix={<UserOutlined />}
                placeholder="请输入用户名" 
                disabled={!!editingUser}
              />
            </Form.Item>

            <Form.Item
              name="email"
              label="邮箱"
              rules={[
                { required: true, message: '请输入邮箱地址' },
                { type: 'email', message: '请输入有效的邮箱地址' }
              ]}
            >
              <Input 
                prefix={<MailOutlined />}
                placeholder="请输入邮箱地址" 
              />
            </Form.Item>

            {!editingUser && (
              <Form.Item
                name="password"
                label="密码"
                rules={[
                  { required: true, message: '请输入密码' },
                  { min: 6, message: '密码长度至少6位' }
                ]}
              >
                <Input.Password 
                  prefix={<LockOutlined />}
                  placeholder="请输入密码" 
                />
              </Form.Item>
            )}

            <Form.Item
              name="role"
              label="角色"
              rules={[{ required: true, message: '请选择用户角色' }]}
            >
              <Select placeholder="请选择用户角色">
                <Option value="user">普通用户</Option>
                <Option value="super_admin">超级管理员</Option>
              </Select>
            </Form.Item>

            <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
              <Space>
                <Button onClick={() => setModalVisible(false)}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  {editingUser ? '更新' : '创建'}
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </Content>
    </Layout>
  )
}

export default UserManagement